package com.duyj.business.service.impl;

import com.duyj.business.service.BusinessService;
import com.duyj.client.order.feign.OrderFeignService;
import com.duyj.client.order.model.Order;
import com.duyj.client.stock.feign.StockFeignService;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Service
public class BusinessServiceImpl implements BusinessService {

    private static final Logger logger = org.slf4j.LoggerFactory.getLogger(BusinessServiceImpl.class);

    @Autowired
    private StockFeignService stockFeignService;

    @Autowired
    private OrderFeignService orderFeignService;

    @Override
    @GlobalTransactional(timeoutMills = 300000, name = "springboot-feign-seata-xa")
    public void doBusiness(String goodsCode, int goodsNumber, String userName) {
        logger.info("Service Begin ... xid: " + RootContext.getXID());
        stockFeignService.updateStock(goodsCode);
        String stockName = stockFeignService.getStockName(goodsCode);
        Order order = new Order();
        order.setGoodsCode(goodsCode);
        order.setGoodsNumber(goodsNumber);
        order.setUserName(userName);
        order.setGoodsName(stockName);
        order.setAmount(BigDecimal.valueOf(goodsNumber * 2L));
        orderFeignService.postOrder(order);
        //throw new RuntimeException("force rollback!");
    }

    @Override
    public void checkOrder(Long id) {
        Order order = orderFeignService.getOrder(id);
        System.out.println(order);
    }

}
